package com.room.search.web.rest;

import com.room.search.core.page.TableDataInfo;
import com.room.search.repository.RoomCommunityRepository;
import com.room.search.response.RoomResult;
import com.room.search.service.RoomCommunityService;
import com.room.search.service.dto.CityAndDistrictDTO;
import com.room.search.service.dto.GetAllByProvinceAndCityDTO;
import com.room.search.service.dto.RoomCommunityDTO;
import com.room.search.service.dto.community.GetCommunityListDTO;
import com.room.search.web.rest.errors.BadRequestAlertException;
import io.swagger.annotations.ApiModelProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Objects;
import java.util.Optional;

/**
 * REST controller for managing {@link com.room.search.domain.RoomCommunity}.
 */
@RestController
@RequestMapping("/api")
public class RoomCommunityResource {

    private final Logger log = LoggerFactory.getLogger(RoomCommunityResource.class);

    private static final String ENTITY_NAME = "roomCommunity";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final RoomCommunityService roomCommunityService;

    private final RoomCommunityRepository roomCommunityRepository;

    public RoomCommunityResource(RoomCommunityService roomCommunityService, RoomCommunityRepository roomCommunityRepository) {
        this.roomCommunityService = roomCommunityService;
        this.roomCommunityRepository = roomCommunityRepository;
    }

    /**
     * {@code POST  /room-communities} : Create a new roomCommunity.
     */
    @PostMapping("/community_add")
    public RoomResult createRoomCommunity(@Valid @RequestBody RoomCommunityDTO dto) {
        log.debug("REST request to save RoomCommunity : {}", dto);
        if (dto.getId() != null) {
            throw new BadRequestAlertException("A new roomCommunity cannot already have an ID", ENTITY_NAME, "idExists");
        }
        return roomCommunityService.save(dto);
    }

    /**
     * {@code PATCH  /room-communities/:id} : Partial updates given fields of an existing roomCommunity, field will ignore if it is null
     *
     * @param id               the id of the roomCommunityDTO to save.
     * @param roomCommunityDTO the roomCommunityDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated roomCommunityDTO,
     * or with status {@code 400 (Bad Request)} if the roomCommunityDTO is not valid,
     * or with status {@code 404 (Not Found)} if the roomCommunityDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the roomCommunityDTO couldn't be updated.
     */
    @PatchMapping(value = "/community_edit/{id}", consumes = {"application/json", "application/merge-patch+json"})
    public ResponseEntity<RoomCommunityDTO> partialUpdateRoomCommunity(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody RoomCommunityDTO roomCommunityDTO
    ) {
        log.debug("REST request to partial update RoomCommunity partially : {}, {}", id, roomCommunityDTO);
        if (roomCommunityDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, roomCommunityDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!roomCommunityRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<RoomCommunityDTO> result = roomCommunityService.partialUpdate(roomCommunityDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, roomCommunityDTO.getId().toString())
        );
    }

    /**
     *
     */
    @GetMapping("/community_list")
    public TableDataInfo getAllRoomCommunities(GetCommunityListDTO dto) {
        log.debug("REST request to get all RoomCommunities");
        return roomCommunityService.getAllRoomCommunities(dto);
    }

    /**
     * {@code GET  /room-communities/:id} : get the "id" roomCommunity.
     *
     * @param id the id of the roomCommunityDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the roomCommunityDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/community/{id}")
    public RoomResult getRoomCommunity(@PathVariable Long id) {
        log.debug("REST request to get RoomCommunity : {}", id);
        RoomCommunityDTO roomCommunityDTO = roomCommunityService.findOne(id).orElse(null);
        if (roomCommunityDTO == null) {
            return RoomResult.error("无该小区的任何信息");
        }
        return RoomResult.success().put("data", roomCommunityDTO);
    }

    /**
     * {@code DELETE  /room-communities/:id} : delete the "id" roomCommunity.
     *
     * @param id the id of the roomCommunityDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/room-communities/{id}")
    public ResponseEntity<Void> deleteRoomCommunity(@PathVariable Long id) {
        log.debug("REST request to delete RoomCommunity : {}", id);
        roomCommunityService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
            .build();
    }

    /**
     * 首页
     */
    @ApiModelProperty("根据省份和市选择对于的社区")
    @GetMapping("/community/area")
    public RoomResult getCommunityByProvinceAndCity(GetAllByProvinceAndCityDTO dto) {
        return roomCommunityService.getCommunityByProvinceAndCity(dto);
    }


    @GetMapping("/community/by_district")
    public TableDataInfo getAllCommunityByDistrict(CityAndDistrictDTO dto) {
        return roomCommunityService.getAllCommunityByDistrict(dto);
    }
}
